package com.zeus.gen.generate.service.impl;

import com.zeus.gen.base.dto.Query;
import com.zeus.gen.base.service.impl.BaseServiceImpl;
import com.zeus.gen.generate.CodeGenerator;
import com.zeus.gen.generate.model.DbColumn;
import com.zeus.gen.generate.model.DbTable;
import com.zeus.gen.generate.model.Generate;
import com.zeus.gen.generate.service.GenerateService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * GeneratorService实现
 *
 * @author liuwei
 * @version 2018-08-07 11:05:10
 */
@Service("generateService")
public class GenerateServiceImpl extends BaseServiceImpl<Generate> implements GenerateService {
    private static Logger LOGGER = LoggerFactory.getLogger(GenerateServiceImpl.class);

    @Override
    public Class<Generate> getEntityClass() {
        return Generate.class;
    }

    @Override
    public DbTable queryTable(String tableName) {
        Query query = new Query();
        query.append("name", tableName);
        return super.findOne(query, "queryTable");
    }

    @Override
    public List<DbColumn> queryColumns(String tableName) {
        Query query = new Query();
        query.append("name", tableName);
        List<DbColumn> columnList = super.findList(query, "queryColumns");
        return columnList;
    }

    @Override
    public byte[] generateCode(Generate generate, String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            DbTable table = this.queryTable(tableName);
            //查询列信息
            List<DbColumn> columns = this.queryColumns(tableName);
            table.setDbColumnList(columns);
            //生成代码
            CodeGenerator.generate(generate, table, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}